package com.dongdongqiang.daogenerator.utils;

import com.dongdongqiang.daogenerator.exception.TableNotFoundException;
import com.dongdongqiang.daogenerator.pojo.TableColumn;
import com.dongdongqiang.daogenerator.pojo.TableMeta;
import com.dongdongqiang.daocomparator.pojo.DbTableMetaInfoDiffVO;
import com.dongdongqiang.daocomparator.pojo.DbTableMetaInfoVO;
import com.dongdongqiang.daogenerator.tablemetabuilder.TableMetaContext;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 将数据库的表转换为TableMeta
 * Created by ZZB on 2017/11/16.
 */
public class EntityCompareToDbUtils {
    /**
     * 通过表名获取TableMeta
     */
    public static List<DbTableMetaInfoVO> obtainByClass(Class clazz, Connection connection) throws SQLException, TableNotFoundException {
        TableMeta tableMeta = TableMetaContext.obtainByClazz(clazz);
        String tableName = tableMeta.getTableName();
        String primaryKey = tableMeta.getPrimaryKeyColumn().getColumnName();
        return DatabaseUtils.getTableMetas(connection, tableName, primaryKey);
    }

    public static List<DbTableMetaInfoVO> buildByTableMeta(TableMeta tableMeta) throws SQLException {
        List<TableColumn> tableColumns = tableMeta.getTableColumns();
        return tableColumns.stream().map(tableColumn -> {
            DbTableMetaInfoVO dbTableMetaInfoVO = new DbTableMetaInfoVO();
            dbTableMetaInfoVO.setName(tableColumn.getColumnName());
            dbTableMetaInfoVO.setTypeName(tableColumn.getColumnType());
            dbTableMetaInfoVO.setMaxLength(tableColumn.getMaxLength());
            dbTableMetaInfoVO.setPrecision(tableColumn.getPrecision());
            dbTableMetaInfoVO.setScale(tableColumn.getScale());
            dbTableMetaInfoVO.setNullable(tableColumn.getNullable());
            dbTableMetaInfoVO.setPrimaryKey(tableColumn.getPrimaryKey());
            dbTableMetaInfoVO.setDefaultValue(tableColumn.getDefaultValue());
            return dbTableMetaInfoVO;
        }).collect(Collectors.toList());
    }

    public static DbTableMetaInfoDiffVO compare(Class clazz, Connection connection) throws SQLException {
        DbTableMetaInfoDiffVO vo = new DbTableMetaInfoDiffVO();
        TableMeta tableMeta = TableMetaContext.obtainByClazz(clazz);
        try {
            List<DbTableMetaInfoVO> dbTableMetaInfoVOS = obtainByClass(clazz, connection);

        } catch (SQLException e) {
            vo.setDiff(true);
            vo.setDiffMessages(Collections.singletonList(e.getMessage()));
            return vo;
        } catch (TableNotFoundException e) {
            vo.setDiff(true);
            DatabaseUtils.createTableDDL(tableMeta.getTableName(), connection,buildByTableMeta(tableMeta) );
            vo.setDiffMessages(Collections.singletonList("表["+tableMeta.getTableName()+"]不存在！"));
            return vo;
        }
    }
}
